//头部与尾部复用
define(["jquery","template","cookie"],function($template){
	//利用面向对象的方法
	function Header(){
		this.load();
		
//		this.h_amount();
	}
	Header.prototype = {
		constructor: Header,
		// 加载头部与尾部
		load: function(){
			//头部
//			$.get("/html/include/header.html",$.proxy(this.headerHandler,this));
			//$.get("/html/include/header.html",this.headerHandler.bind(this));
			//异步加载
			$("header").load("/html/include/header.html",()=>{
				this.h_amount();
				this.verify();
				this.addlistener();
				// 为“搜索”框绑定按键事件
				$("#serch").keyup(this.searchHandler);
				// 为 ".suggest" 的孩子 div 绑定点击事件：事件委派
				$(".suggest").on("click","div",this.suggestHandler);
			});
				//尾部
			$("footer").load("/html/include/footer.html",()=>{
				$(".up").on("click",this.upselect);
			});
			
		},
		upselect:function(){
			var status = $(".h_footmenu").css("height");
			if(status == "0px"){
				$(".h_footmenu").animate({height: 128},500);
				$(".footer_i").css("background","url(/images/f_listbottom.jpg)no-repeat center");
				
			}else{
				$(".h_footmenu").animate({height: 0},500);
				$(".footer_i").css("background","url(/images/f_listtop.jpg)no-repeat center");

			}
			
		},
		addlistener:function(){
			$(".out").on("click",$.proxy(this.outhandler, this));
			
		},
		outhandler:function(event){
			$.cookie("login-user",null,{path:"/"});
			$.cookie("sum",0,{path:"/"});
			$.cookie("cart",null,{path:"/"});
			location.reload();
			return false;
		},
		verify: function(){
				$.cookie.json = true;
				var user= $.cookie("login-user");
				if(user){
					$(".username").text("嗨！" + user);
					$(".login").hide().siblings(".register").hide().siblings(".username").show().siblings(".out").show();
				}else{
					$(".login").show().siblings(".register").show().siblings(".username").hide().siblings(".out").hide();
				}
		},
			
		// 处理搜索框事件
		searchHandler: function() {
			var 
				word = $(this).val(),
				url = `https://suggest.taobao.com/sug?code=utf-8&q=${word}&callback=?`;
			$.getJSON(url, function(data){
				var html = "";
				data.result.forEach(function(curr){
					html += `<div>${curr[0]}</div>`;
				});
				$(".suggest").html(html);
			});			
		},
		//头部显示购物车数量
		h_amount:function(){
			var sum_amount = $.cookie("sum");
			$(".head_amount").text(sum_amount);
		},
		// 点击提示
		suggestHandler: function() {
			$("#serch").val($(this).text());
			//移除下拉列表框
			$(".suggest").empty();
		}
	}
	
	new Header();
});